from django.template.loader import render_to_string
from django.template.context import RequestContext, Context
from django.shortcuts import render_to_response
from django.utils.translation import ugettext as __
from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse

INVITE_IN_TWO_STEPS = getattr(settings, 'INVITE_IN_TWO_STEPS', True)
INVITES_PER_USER = getattr(settings, 'INVITES_PER_USER', None)

from models import Invite
from forms import EmbedInviteForm, InviteForm
from decorators import invite_required

if 'mailer' in settings.INSTALLED_APPS:
	from mailer import send_mail
else:
	from django.core.mail import send_mail

def _redirect_or_render(success, message, **kwargs):
	if kwargs['redirect']:
		if callable(kwargs['redirect']):
				return kwargs['redirect'](kwargs['request'], kwargs.get('invite', None), kwargs['additional_context'], kwargs['additional_data'], success=success, message=message)
		else:
				return HttpResponseRedirect(kwargs['redirect'])
	else:
		return render_to_response(kwargs['template_name'], {'form':kwargs.get('form',EmbedInviteForm())}, RequestContext(kwargs['request'], kwargs['additional_context']))
		
#sends invite to user. returns invite, sent.
#Invite, True if Invite was created and has been sent succesfuly
#Invite, False if it has been already sent.
def send_invite(sender, email, site_name,
           subject_template='invites/mail_subject.txt', body_template='invites/mail_body.txt',
           context={}, additional_context={},  additional_data=None):
	try:
		invite = Invite.objects.get(sender=sender, email=email)
		return invite, False
	except Invite.DoesNotExist:
		pass
	invite = Invite(sender=sender, email=email)
	invite.data = additional_data
	invite.save()

	from common.request import container
	invite_url = container.request.build_absolute_uri(reverse('accept_invite', kwargs={'invite_key':invite.key}))
	
	context.update(sender=sender, invite=invite, invite_url=invite_url, site_name=site_name, **additional_context)
	context = Context(context)
	subject = render_to_string(subject_template, context)
	body = render_to_string(body_template, context)
	send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, (email, ))
	return invite, True

def send(request, site_name,
         template_name='invites/send.html', subject_template='invites/mail_subject.txt',
         body_template='invites/mail_body.txt', prefilled_body_template='invites/prefilled_mail_body.txt',
         additional_context={}, additional_data=None, redirect=None):

	if not request.user.is_superuser and INVITES_PER_USER and (request.user.invites_left <= 0):
		request.user.message_set.create(message=__("No invites left"))
		return _redirect_or_render(success=False, message=__("No invites left"), **locals())

	if request.method == 'POST':
		form = EmbedInviteForm(request.POST)
		if form.is_valid():

			if INVITE_IN_TWO_STEPS:
				if 'mail_body' not in request.POST:
					context = form.cleaned_data
					context.update(additional_context, sender=request.user, site_name=site_name)
					form = InviteForm(initial = {'recipient_email': form.cleaned_data['recipient_email'],
												'recipient_name': form.cleaned_data['recipient_name'],
												'mail_subject':render_to_string(subject_template, context),
												'mail_body':render_to_string(prefilled_body_template, context)})
					return render_to_response(template_name, {'form':form}, RequestContext(request, additional_context))
				else:
					form = InviteForm(request.POST)
					if not form.is_valid():
						return render_to_response(template_name, {'form':form}, RequestContext(request, additional_context))

			invite, sent = send_invite(sender=request.user, site_name=site_name, email=form.cleaned_data['recipient_email'],
							subject_template=subject_template, body_template=body_template,
							context=form.cleaned_data, additional_context=additional_context,
							additional_data=additional_data)
			if sent:
				message = __("Invite sent successfuly")
			else:
				message = __("Invite already sent")
			request.user.message_set.create(message=message)
			return _redirect_or_render(success=sent, **locals())

	else:
		form =  EmbedInviteForm()
	return render_to_response(template_name, {'form':form}, RequestContext(request, additional_context))

#its just demo of accepting invite
@invite_required
def accept(request, invite):
	invite.delete()
	return HttpResponseRedirect('/') 

def index(request):
	return HttpResponseRedirect(reverse('invites.views.send'))
